<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/8/20
 * Time: 10:55
 */

namespace app\modules\controllers;

use app\models\Profile;
use app\models\User;
use Yii;
use yii\data\Pagination;

class UserController extends CommonController
{
    protected $mustLogin = ['users','reg' , 'del'];
    public function actionUsers()
    {
        $this->layout = 'layout1';
        $model = User::find()->joinWith('profile');
        $count = $model->count();
        $pages = new Pagination(['pageSize' => Yii::$app->params['pageSize']['user'],'totalCount' => $count]);
        $data = $model->offset($pages->offset)->limit($pages->limit)->all();
        return $this->render('users',['users' => $data, 'pager' => $pages]);
    }

    public function actionReg()
    {
        $this->layout = 'layout1';
        $model = new User();
        if (Yii::$app->request->isPost) {
            if($model->reg(Yii::$app->request->post())){
                Yii::$app->session->setFlash('info', '添加成功');
            }
        }
        $model->userpass = '';
        $model->repass = '';
        return $this->render('reg',['model' => $model]);
    }

    public function actionDel()
    {
        try {
            $userid = (int)Yii::$app->request->get('userid');
            if (empty($userid)) {
                throw new \Exception("参数丢失");
            }
            $tran = Yii::$app->db->beginTransaction();
            if ($obj = Profile::find()->where(['userid' => $userid])->one()){
                $res = Profile::deleteAll(['userid' => $userid]);
                if (empty($res)) {
                    throw new \Exception();
                }
            }
            if (!User::deleteAll(['userid' => $userid])) {
                throw new \Exception();
            }
            $tran->commit();
        } catch (\Exception $e) {
            if (Yii::$app->db->beginTransaction()){
                $tran->rollback();
            }
        }
        return $this->redirect(['user/users']);
    }
}